import { FormSchema } from '/@/components/Table';
import { Button } from '/@/components/Button';
import {
  getEntityDeviceList,
  getTenantAssetInfos,
  getTenantEntityViews,
  getTenant,
  getCustomerList,
  getUsers,
  getDashboards,
  getEdge,
} from '/@/api/thingsborad/entity/entity';

export const customerSchemas: FormSchema[] = [
  {
    field: 'customer',
    component: 'Select',
    componentProps: {
      options: [
        { value: 'customerA', label: 'customerA' },
        { value: 'customerB', label: 'customerB' },
        { value: 'customerC', label: 'customerC' },
      ],
    },
    label: '请选择客户分配实体视图',
    colProps: {
      span: 24,
    },
    required: true,
  },
];

export const deviceSchemas: FormSchema[] = [
  {
    field: 'name',
    component: 'Input',
    label: '名称',
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'deviceConfiguration',
    component: 'Input',
    label: '设备配置',
    renderComponentContent: (value) => {
      return {
        suffix: () => {
          return (
            <Button
              v-show={value?.values?.deviceConfiguration == ''}
              type="text"
              onClick={() => console.log('createDevice')}
            >
              创建
            </Button>
          );
        },
      };
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'label',
    component: 'Input',
    label: '标签',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'field2',
    component: 'Input',
    subLabel: '选择将分发到设备的固件',
    labelWidth: 400,
    label: '',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'field2',
    component: 'Input',
    subLabel: '选择将分发到设备的软件',
    labelWidth: 400,
    label: '',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'isGateway',
    component: 'Switch',
    label: '是否网关',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'isCover',
    component: 'Switch',
    label: '覆盖已连接设备的活动时间',
    colProps: {
      span: 24,
    },
    ifShow: (value) => {
      return value?.model?.isGateway;
    },
  },
  {
    field: 'remark',
    component: 'InputTextArea',
    label: '说明',
    colProps: {
      span: 24,
    },
  },
];

// 添加键值对
export const addKeyValueSchema: FormSchema[] = [
  {
    field: 'keyName',
    label: '键名',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: '键名*',
      };
    },
    ifShow: () => {
      return true;
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'valueType',
    label: '值类型',
    component: 'Select',
    componentProps: {
      placeholder: '请选择值类型',
      listHeight: 160,
      allowClear: false,
      options: [
        { label: '字符串', value: 'string' },
        { label: '整数', value: 'integer' },
        { label: '双精度小数', value: 'decimal' },
        { label: '布尔值', value: 'boolean' },
        { label: 'JSON', value: 'json' },
      ],
    },
    colProps: {
      span: 24,
    },
    required: true,
    defaultValue: 'string',
  },
  {
    field: 'stringValue',
    label: '字符串值',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: '字符串值*',
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'string';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'integerValue',
    label: '整数值',
    component: 'InputNumber',
    componentProps: () => {
      return {
        placeholder: '整数值*',
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'integer';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'decimalValue',
    label: '双精度小数',
    component: 'InputNumber',
    componentProps: () => {
      return {
        placeholder: '双精度小数*',
        stringMode: true,
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'decimal';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'booleanValue',
    label: '假',
    component: 'Checkbox',
    componentProps: ({ formActionType }) => {
      return {
        onChange: (e: any) => {
          const { updateSchema } = formActionType;
          updateSchema({ field: 'booleanValue', label: e.target.checked ? '真' : '假' });
        },
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'boolean';
    },
    defaultValue: false,
    colProps: {
      span: 24,
    },
  },
  {
    field: 'jsonValue',
    label: 'JSON',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: 'JSON值*',
      };
    },
    rules: [
      {
        required: true,
        validator: (_, value) => {
          const isJSON = (value: string) => {
            try {
              const json = JSON.parse(value);
              return typeof json === 'object';
            } catch (err) {
              return false;
            }
          };
          if (!value) return Promise.reject('不能为空');
          if (!isJSON(value) || value == 'null' || value == '{}') {
            return Promise.reject('请输入正确的JSON格式');
          }
          return Promise.resolve();
        },
      },
    ],
    defaultValue: '{}',
    ifShow: (value) => {
      return value?.model?.valueType == 'json';
    },
    colProps: {
      span: 24,
    },
  },
];
// 编辑属性
export const editAttributeSchema: FormSchema[] = [
  {
    field: 'valueType',
    label: '值类型',
    component: 'Select',
    componentProps: () => {
      return {
        placeholder: '请选择值类型',
        listHeight: 160,
        allowClear: false,
        options: [
          { label: '字符串', value: 'string' },
          { label: '整数', value: 'integer' },
          { label: '双精度小数', value: 'decimal' },
          { label: '布尔值', value: 'boolean' },
          { label: 'JSON', value: 'json' },
        ],
      };
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'stringValue',
    label: '字符串值',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: '字符串值*',
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'string';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'integerValue',
    label: '整数值',
    component: 'InputNumber',
    componentProps: () => {
      return {
        placeholder: '整数值*',
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'integer';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'decimalValue',
    label: '双精度小数',
    component: 'InputNumber',
    componentProps: () => {
      return {
        placeholder: '双精度小数*',
      };
    },
    ifShow: (value) => {
      return value?.model?.valueType == 'decimal';
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'booleanValue',
    label: '假',
    component: 'Checkbox',
    ifShow: (value) => {
      return value?.model?.valueType == 'boolean';
    },
    defaultValue: false,
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'jsonValue',
    label: 'JSON',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: 'JSON值*',
      };
    },
    defaultValue: '{}',
    ifShow: (value) => {
      return value?.model?.valueType == 'json';
    },
    rules: [
      {
        required: true,
        validator: (_, value) => {
          const isJSON = (value: string) => {
            try {
              const json = JSON.parse(value);
              return typeof json === 'object';
            } catch (err) {
              return false;
            }
          };
          if (!value) return Promise.reject('不能为空');
          if (!isJSON(value) || value == 'null' || value == '{}') {
            return Promise.reject('请输入正确的JSON格式');
          }
          return Promise.resolve();
        },
      },
    ],
    colProps: {
      span: 24,
    },
    required: true,
  },
];
// 添加关联
export const addAssociationSchemas: FormSchema[] = [
  {
    field: 'associationType',
    component: 'Select',
    componentProps: {
      placeholder: '关联类型*',
      options: [
        {
          label: 'Contains',
          value: 'Contains',
        },
        {
          label: 'Manages',
          value: 'Manages',
        },
      ],
    },
    label: '关联类型',
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'toEntity',
    component: 'Select',
    componentProps: ({ formActionType }) => {
      // let timeout: any;
      // const fetchData = async (inputValue: any) => {
      //   const data = await getEntityDeviceList({
      //     page: 0,
      //     pageSize: 50,
      //     sortProperty: 'createdTime',
      //     sortOrder: 'ASC',
      //     textSearch: inputValue,
      //   });
      // };
      return {
        listHeight: 160,
        placeholder: '类型*',
        options: [
          { label: '设备', value: 'DEVICE' },
          { label: '资产', value: 'ASSET' },
          { label: '实体视图', value: 'ENTITY_VIEW' },
          { label: '租户', value: 'TENANT' },
          { label: '客户', value: 'CUSTOMER' },
          { label: '用户', value: 'USER' },
          { label: '仪表盘', value: 'DASHBOARD' },
          { label: '边缘', value: 'EDGE' },
        ],
        onChange: (val) => {
          const { updateSchema } = formActionType;
          let api: any;
          let params: any = {
            page: 0,
            pageSize: 50,
            sortProperty: 'createdTime',
            sortOrder: 'ASC',
          };
          switch (val) {
            case 'DEVICE':
              api = getEntityDeviceList;
              break;
            case 'ASSET':
              api = getTenantAssetInfos;
              break;
            case 'ENTITY_VIEW':
              api = getTenantEntityViews;
              break;
            case 'TENANT':
              api = getTenant;
              params = '租户id';
              break;
            case 'CUSTOMER':
              api = getCustomerList;
              break;
            case 'USER':
              api = getUsers;
              break;
            case 'DASHBOARD':
              api = getDashboards;
              break;
            case 'EDGE':
              api = getEdge;
              break;
          }
          updateSchema({
            field: 'entityList',
            componentProps: {
              placeholder: '实体列表',
              listHeight: 160,
              mode: 'tags',
              showSearch: true,
              showArrow: false,
              api,
              params,
              resultField: 'data',
              labelField: 'name',
              valueField: 'id.id',
              immediate: true,
              // 远程搜索
              // filterOption: async (inputValue) => {
              //   if (timeout) {
              //     clearTimeout(timeout);
              //     timeout = null;
              //   }
              //   timeout = setTimeout(fetchData.bind(null, inputValue), 300);
              // },
            },
          });
        },
      };
    },
    label: '到实体',
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'entityList',
    component: 'ApiSelect',
    label: '实体',
    ifShow: ({ values }) => {
      return values?.toEntity;
    },
    colProps: {
      span: 24,
    },
    required: true,
  },
  {
    field: 'jsonValue',
    component: 'InputTextArea',
    label: '附加信息（JSON）',
    slot: 'jsonSlot',
    colProps: {
      span: 24,
    },
    rules: [
      {
        validator: (_, value) => {
          const isJSON = (value: string) => {
            try {
              const json = JSON.parse(value);
              return typeof json === 'object';
            } catch (err) {
              return false;
            }
          };
          if (!value) return Promise.resolve();
          if (!isJSON(value) || value == 'null') {
            return Promise.reject('请输入正确的JSON格式');
          }
          return Promise.resolve();
        },
      },
    ],
  },
];
// 编辑关联
export const editAssociationSchemas: FormSchema[] = [
  {
    field: 'jsonValue',
    component: 'InputTextArea',
    label: '附加信息（JSON）',
    slot: 'jsonSlot',
    colProps: {
      span: 24,
    },
    rules: [
      {
        validator: (_, value) => {
          const isJSON = (value: string) => {
            try {
              const json = JSON.parse(value);
              return typeof json === 'object';
            } catch (err) {
              return false;
            }
          };
          if (!value) return Promise.resolve();
          if (!isJSON(value) || value == 'null') {
            return Promise.reject('请输入正确的JSON格式');
          }
          return Promise.resolve();
        },
      },
    ],
  },
];
// 删除遥测
export const deleteTelemetrySchemas: FormSchema[] = [
  {
    field: 'deleteStrategy',
    component: 'Select',
    label: '删除策略',
    componentProps: {
      listHeight: 160,
      allowClear: false,
      options: [
        { label: 'Delete all data', value: 'DeleteAllData' },
        { label: 'Delete all data except latest value', value: 'DeleteAllDataExceptLatestValue' },
        { label: 'Delete latest value', value: 'DeleteLatestValue' },
        { label: 'Delete all data for time period', value: 'DeleteAllDataForTimePeriod' },
      ],
    },
    defaultValue: 'DeleteAllData',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'rewrite',
    component: 'Switch',
    label: 'Rewrite latest value',
    ifShow: (value) => {
      return (
        value?.model?.deleteStrategy == 'DeleteLatestValue' ||
        value?.model.deleteStrategy == 'DeleteAllDataForTimePeriod'
      );
    },
    defaultValue: true,
  },
  {
    field: 'startTime',
    component: 'DatePicker',
    label: 'endTime',
    ifShow: (value) => {
      return value?.model.deleteStrategy == 'DeleteAllDataForTimePeriod';
    },
    defaultValue: true,
  },
  {
    field: 'endTime',
    component: 'DatePicker',
    label: 'startTime',
    ifShow: (value) => {
      return value?.model.deleteStrategy == 'DeleteAllDataForTimePeriod';
    },
    defaultValue: true,
  },
];
